<?php
/**
 * @author spenceryg
 * @date 2023/5/13
 * @time 10:52 上午
 * @focus love & life
 */


namespace app\common\lib;


use app\common\model\GptToken;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Middleware;
use think\facade\Db;
use think\facade\Log;
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Response;
use GuzzleHttp\RequestOptions;
use GuzzleHttp\Promise;
use GuzzleHttp\Exception\RequestException;


class Chat2
{

    public static function chatTest()
    {


        $callback = function ($ch, $data) {
            Log::channel('gpt')->info($ch);
            Log::channel('gpt')->info($data);
        };

        $token = GptToken::where('id', '=', 1)->value('token');
        $headers = [
            'Accept: application/json',
            'Content-Type: application/json',
            'Authorization: Bearer ' . $token
        ];
        $post = [
            'model' => 'gpt-3.5-turbo',
            'messages' => [
                [
                    "role" => "user",
                    "content" => '写一个php函数 用来提取html中的a标签'
                ],
            ],
            'stream' => true
        ];
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_URL, 'https://api.openai.com/v1/chat/completions');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post));
        curl_setopt($ch, CURLOPT_WRITEFUNCTION, $callback);
        curl_exec($ch);
    }


    public static function test()
    {
        $client = new Client();

// 创建自定义处理器栈
        $stack = HandlerStack::create();

// 添加一个回调处理程序来处理每次接收到的响应数据
        $stack->push(Middleware::mapResponse(function (Response $response) {
            // 获取响应流
            $stream = $response->getBody();

            // 逐步读取数据并触发回调函数处理
            while (!$stream->eof()) {
                $data = $stream->read(4096); // 每次读取 4096 字节

                // 在这里调用自定义的回调函数处理数据
                self::handleResponseData($data);
            }

            // 关闭流
            $stream->close();

            return $response;
        }));

// 创建带有自定义处理器栈的客户端
        $client = new Client(['handler' => $stack]);

        $token = GptToken::where('id', '=', 1)->value('token');

        $post = [
            'model' => 'gpt-3.5-turbo',
            'messages' => [
                [
                    "role" => "user",
                    "content" => '写一个php函数 用来提取html中的a标签'
                ],
            ],
            'stream' => true
        ];
        // 发起请求
        $request = $client->postAsync('https://api.openai.com/v1/chat/completions', [
                'stream' => true,
                'json' => $post,
                'headers' => [
                    'Authorization' => "Bearer {$token}",
                ]
            ]
        );

// 处理异步请求
        $request->then(
            function (Response $response) {
                // 请求成功完成时的回调函数
                echo "Request completed successfully.\n";
            }
//            ,
//            function (RequestException $exception) {
//                // 请求发生错误时的回调函数
//                echo "Request encountered an error.\n";
//                echo $exception->getMessage();
//            }
        )->wait();

// 自定义回调处理函数

    }

    public static function handleResponseData($data)
    {
        // 在这里实现你的自定义回调处理逻辑
        // 可以对读取的数据进行实时处理、解析、存储等操作
        // 示例：将数据输出到标准输出

        echo $data;
        ob_flush();
        flush();
        Log::channel('gpt')->info($data);
    }
}
